<?
class ProcatController extends BaseController{
    var $type = 'product';
    var $filter;
    var $filter_array = array(
        'min'=>0,
        'max'=>0,
        'fac'=>0,
        'color'=>'',
        'style'=>'',
        'uniform'=>'',
        'func'=>''
    );
    var $current_url = '';
    var $current_query_string = '';
    var $class_filter_selected = 'filter_selected';
    const MONEY_RATIO = 1000000;
    var $order_type = array(
        1=>'Giá tăng dần',
        2=>'Giá giảm dần',
        3=>'Hàng mới'
    );
    var $total_record = 0;
    var $start = 0;
    var $limit = 10;
    var $list_product = array();

    public function __construct($type){
        parent::__construct();
        $this->type = $type;
        $this->filter = new Filter();
        //Lấy url hiện tại, loại bỏ query string
        $current_url = explode('?',$_SERVER['REQUEST_URI']);
        $this->current_url = $current_url[0];
        //lấy query string hiện tại, remove html
        $this->current_query_string = urldecode(removeHTML(removeScript(getURL(0,0,0,1))));
        //bỏ dấu hỏi ở đầu và cuối do hàm getUrl tạo ra
        $this->current_query_string = trim($this->current_query_string,'?');
        if($this->current_query_string){
            //Cắt các tham số
            $array_parse_url = explode('&',$this->current_query_string);
            $filter_array = array();

            foreach($array_parse_url as $filter){
                //cắt dấu =
                $tmp = explode('=',$filter);
                if(count($tmp) > 2){
                    break;
                }
                //gán field = value
                $filter_array[$tmp[0]] = $tmp[1];
            }
            //đồng bộ mảng filter array
            $this->filter_array = _extend_attributes($filter_array, $this->filter_array);
        }

    }

    //Tạo filter url từ các tiêu chí
    public function generateFilterUrl(){
        $return_url = array();
        //Lặp qua các tiêu chí
        foreach($this->filter_array as $filter=>$value){
            //nếu tiêu chí ko tồn tại thì continue
            if(!$value) continue;
            $return_url[] = $filter . '=' . $value;
        }
        if(!$return_url){
            return $this->current_url;
        }
        $return_url = $this->current_url . '?' . implode('&',$return_url);
        return $return_url;
    }
    //Tạo link remove filter
    public function removeFilterUrl($array_filter_remove){
        $return_url = array();
        //Lặp qua các tiêu chí

        foreach($this->filter_array as $filter=>$value){
            //nếu tiêu chí ko tồn tại thì continue //nếu tiêu chí trùng với tiêu chí cần remove thì continue
            if(is_array($array_filter_remove)){
                if(!$value || in_array($filter,$array_filter_remove)) continue;
            }else{
                if(!$value || $filter == $array_filter_remove) continue;
            }
            $return_url[] = $filter . '=' . $value;
        }
        $return_url = $this->current_url . '?' . implode('&',$return_url);
        return $return_url;
    }

    //reset filter_array trả về khởi tạo
    public function resetFilterArray(){
        $this->filter_array = array(
            'min'=>'',
            'max'=>'',
            'fac'=>'',
            'color'=>'',
            'style'=>'',
            'uniform'=>'',
            'func'=>''
        );
        if($this->current_query_string){
            //Cắt các tham số
            $array_parse_url = explode('&',$this->current_query_string);
            $filter_array = array();

            foreach($array_parse_url as $filter){
                //cắt dấu =
                $tmp = explode('=',$filter);
                if(count($tmp) > 2){
                    break;
                }
                //gán field = value
                $filter_array[$tmp[0]] = $tmp[1];
            }
            //đồng bộ mảng filter array
            $this->filter_array = _extend_attributes($filter_array, $this->filter_array);
        }
    }

    //html bộ lọc giá
    public function getFilterPrice(){
        $attribute = array();
        //print_r($this->filter_array);
        foreach($this->filter->price() as $price){
            //Đồng bộ filter
            $this->filter_array['min'] = $price['min'];
            $this->filter_array['max'] = $price['max'];
            //Tạo link filter
            $gen_url = $this->generateFilterUrl();
            if($this->checkFilterSelected('min',$price['min']) && $this->checkFilterSelected('max',$price['max'])){
                $selected = $this->class_filter_selected;
                //Tạo link remove filter
                $remove_url = $this->removeFilterUrl(array('min','max'));
            }else{
                $remove_url = '';
                $selected = '';
            }
            $tmp = array('text'=>$price['label'],'url'=>$gen_url,'selected'=>$selected,'remove_url'=>$remove_url);
            $attribute[] = $tmp;
        }
        $this->resetFilterArray();
        return ProcatLayout::filter_price($attribute);
    }

    public function getFilterFactory(){
        $attribute = array();
        foreach($this->filter->factory($this->type) as $factory){
            //Đồng bộ filter
            $this->filter_array['fac'] = $factory['fac_id'];
            $gen_url = $this->generateFilterUrl();
            if($this->checkFilterSelected('fac',$factory['fac_id'])){
                $selected = $this->class_filter_selected;
                //Tạo link remove filter
                $remove_url = $this->removeFilterUrl('fac');
            }else{
                $remove_url = '';
                $selected = '';
            }
            $tmp = array('text'=>$factory['fac_name'],'url'=>$gen_url, 'selected'=>$selected,'remove_url'=>$remove_url);
            $attribute[] = $tmp;
        }
        $this->resetFilterArray();
        return ProcatLayout::filter_factory($attribute);
    }

    public function getFilterColor(){
        $attribute = array();
        foreach($this->filter->color() as $color){
            //Đồng bộ filter
            $this->filter_array['color'] = $color;
            $gen_url = $this->generateFilterUrl();
            if($this->checkFilterSelected('color',$color)){
                $selected = $this->class_filter_selected;
                //Tạo link remove filter
                $remove_url = $this->removeFilterUrl('color');
            }else{
                $remove_url = '';
                $selected = '';
            }
            $tmp = array('text'=>$color,'url'=>$gen_url,'selected'=>$selected,'remove_url'=>$remove_url);
            $attribute[] = $tmp;
        }
        $this->resetFilterArray();
        return ProcatLayout::filter_color($attribute);
    }

    public function getFilterStyle(){
        $attribute = array();
        foreach($this->filter->style() as $color){
            //Đồng bộ filter
            $this->filter_array['style'] = $color;
            $gen_url = $this->generateFilterUrl();
            if($this->checkFilterSelected('style',$color)){
                $selected = $this->class_filter_selected;
                //Tạo link remove filter
                $remove_url = $this->removeFilterUrl('style');
            }else{
                $remove_url = '';
                $selected = '';
            }
            $tmp = array('text'=>$color,'url'=>$gen_url,'selected'=>$selected,'remove_url'=>$remove_url);
            $attribute[] = $tmp;
        }
        $this->resetFilterArray();
        return ProcatLayout::filter_style($attribute);
    }

    public function getFilterUniform(){
        $attribute = array();
        foreach($this->filter->uniform() as $color){
            //Đồng bộ filter
            $this->filter_array['uniform'] = $color;
            $gen_url = $this->generateFilterUrl();
            if($this->checkFilterSelected('uniform',$color)){
                $selected = $this->class_filter_selected;
                //Tạo link remove filter
                $remove_url = $this->removeFilterUrl('uniform');
            }else{
                $remove_url = '';
                $selected = '';
            }
            $tmp = array('text'=>$color,'url'=>$gen_url,'selected'=>$selected,'remove_url'=>$remove_url);
            $attribute[] = $tmp;
        }
        $this->resetFilterArray();
        return ProcatLayout::filter_uniform($attribute);
    }

    public function getFilterFunc(){
        $attribute = array();
        foreach($this->filter->func() as $color){
            //Đồng bộ filter
            $this->filter_array['func'] = $color;
            $gen_url = $this->generateFilterUrl();
            if($this->checkFilterSelected('func',$color)){
                $selected = $this->class_filter_selected;
                //Tạo link remove filter
                $remove_url = $this->removeFilterUrl('func');
            }else{
                $selected = '';
                $remove_url = '';
            }
            $tmp = array('text'=>$color,'url'=>$gen_url,'selected'=>$selected,'remove_url'=>$remove_url);
            $attribute[] = $tmp;
        }
        $this->resetFilterArray();
        return ProcatLayout::filter_func($attribute);
    }

    //Query ra list product
    public function selectProductFromFilter(){
        if($this->list_product){
            return $this->list_product;
        }
        $this->resetFilterArray();
        $sql_filter = '';
        $sql_order = '';
        foreach($this->filter_array as $filter=>$value){
            if(!$value) continue;
            switch($filter){
                case 'min':
                    $sql_filter .= ' AND pro_price >= '.($value * self::MONEY_RATIO);
                    break;
                case 'max':
                    $sql_filter .= ' AND pro_price < '.($value * self::MONEY_RATIO);
                    break;
                case 'fac':
                    $sql_filter .= ' AND pro_factory = '.$value;
                    break;
                case 'color':
                    $sql_filter .= ' AND pro_color = "'.$value.'"';
                    break;
                case 'style':
                    break;
                case 'uniform':
                    break;
                case 'func':
                    $sql_filter .= ' AND (pro_special_function LIKE "%'.$value.'%" OR pro_basic_info LIKE "%'.$value.'%")';
                    break;
            }
            if($filter == 'order_type'){
                //sắp xếp sản phẩm
                switch($value){
                    case 1 ://giá giảm dần
                        $sql_order .= ' ORDER BY pro_price DESC';
                        break;
                    case 2 ://giá tăng dần
                        $sql_order .= ' ORDER BY pro_price ASC';
                        break;
                    case 3 : //hàng mới
                        $sql_order .= ' ORDER BY pro_date DESC';
                }
            }
            if($filter == 'page' && $value >=2){
                //In sản phẩm ra theo trang
                $this->start = $this->limit * ($value - 1);
            }
        }
        //Query database
        if(!$this->total_record){
            $db_count = new db_count('SELECT count(pro_id) as count
                                          FROM products
                                          LEFT JOIN categories_multi ON pro_cat_id = cat_id
                                          WHERE pro_active = 1 AND cat_type = "'.$this->type.'" '.$sql_filter . $sql_order);
            $this->total_record = $db_count->total;unset($db_count);
        }
        $db_query = new db_query('SELECT pro_id,pro_name,
                                             pro_price,pro_thumb,pro_hot,pro_new,
                                             pro_promotion
                                  FROM products
                                  LEFT JOIN categories_multi ON pro_cat_id = cat_id
                                  WHERE pro_active = 1 AND cat_type = "'.$this->type.'" '
                                .$sql_filter . $sql_order
                                .' LIMIT '.$this->start.','.$this->limit);

        $list_product = array();
        while($row = mysql_fetch_assoc($db_query->result)){
            $product = array();
            $product['name']       = $row['pro_name'];
            $product['thumb']      = PATH_PICTURE_PRODUCT_SMALL . $row['pro_thumb'];
            $product['id']         = $row['pro_id'];
            $product['price']      = ($row['pro_price'] == 68000000 ? 'Liên hệ' : format_price($row['pro_price']));
            $product['hot']        = $row['pro_hot'];
            $product['new']        = $row['pro_new'];
            $product['gift']       = $row['pro_promotion'];
            $product['url']        = generate_product_detail_url($row);
            $list_product[]        = $product;
        }
        unset($db_query);
        //gán vào list product
        $this->list_product = $list_product;
    }
    public function getProductList(){
        $list_product = $this->selectProductFromFilter();
        return ProcatLayout::list_product_cat($list_product);
    }

    public function checkFilterSelected($filter,$value){
        $this->resetFilterArray();
        if($this->filter_array[$filter] == $value){
            return true;
        }else{
            return false;
        }
    }

    public function getProductOrderUrl($order_type){
        $this->resetFilterArray();
        $this->filter_array['order_type'] = $order_type;
        return $this->generateFilterUrl();
    }

    public function generatePaging(){
        $page = getValue('page');
        if($page == 0)  $page = 1;
        $array_return = array();
        //tổng số trang
        $total_page = (int)($this->total_record / $this->limit);
        //Phép chia có dư - cộng thêm 1 trang cho page
        if($total_page * $this->limit < $this->total_record){
            $total_page++;
        }
        if($total_page == 0){
            return '';
        }
        for($i = 1; $i <= $total_page; $i++ ){
            $this->resetFilterArray();
            $this->filter_array['page'] = $i;
            $gen_url = $this->generateFilterUrl();
            $tmp = array(
                'label'=>$i,
                'class'=>($page == $i ? 'active' : ''),
                'url'=>$gen_url
            );
            $array_return[] = $tmp;
        }
        return ProcatLayout::paging_product($array_return);
    }
}
?>